package com.topisv.tms.web.focus;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.BackupTask;
import com.topisv.tms.entity.BackupTaskOrdeno;
import com.topisv.tms.entity.BatchTask;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.BackupTaskService;
import com.topisv.tms.service.BatchTaskService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.utils.enums.StatusEnums;

import net.sf.json.JSONObject;

/**
 * WMS生成分拣批次
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping(value = "/focusBatchTask")
public class FocusBatchTaskController {
    private static final Logger log = LoggerFactory.getLogger(FocusBatchTaskController.class);

	private final int pageSize=100;

	@Autowired
	private BatchTaskService batchTaskService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;
	@Autowired
	private BackupTaskService backupTaskService;
	@Autowired
	private AreaGroupService areaGroupService;

	private ShiroUser getShiroUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

	/**
	 * 生成分拣批次
	 * 
	 * @param ordenos
	 *            订单列表(:号分割)
	 * @param orderType
	 *            订单类型
	 * @param customerCode
	 *            商家编码
	 * @param number
	 *            数量(每个分拣批次的数量)
	 * @param areaGroupLists
	 *            数据格式(网点编码:网点名称)
	 * @param ordenoSourceCode
	 *            数据源编码
	 * @param warehouseCode
	 *            客户仓库编码
	 * @param response
	 */
	@RequestMapping(value = "ajaxOrdenosCreateBatchTask")
	public void ajaxOrdenosCreateBatchTask(
			@RequestParam(value = "ordenos") String ordenos,
			@RequestParam(value = "orderType") String orderType,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "number", defaultValue = "1000") int number,
			@RequestParam(value = "areaGroupLists") String areaGroupLists,
			@RequestParam(value = "ordenoSourceCode") String ordenoSourceCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletResponse response) {
		JSONObject json = null;
		PrintWriter out = null;
		ShiroUser user = getShiroUser();
		Customers customers = null;
		try {
			log.info("开始生成分拣批次");
			log.info("ordenos=" + ordenos);
			log.info("orderType=" + orderType);
			log.info("customerCode=" + customerCode);
			log.info("number=" + number);
			log.info("ordenoSourceCode=" + ordenoSourceCode);
			json = new JSONObject();
			out = response.getWriter();
			customers = customersService.findByCustomerCode(customerCode);
			if (customers == null) {
				json.put("status", "-1");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				return;
			}
			if (ordenos == null || "".equals(ordenos)) {
				json.put("status", "-1");
				json.put("content", "没有订单");
				out.print(json.toString());
				return;
			}
			// WMS集发出库
			List<BatchTask> batchTasks = batchTaskService.createBatchTask(
					warehouseCode, ordenos, user.jobuuid, orderType,
					customerCode, number, areaGroupLists, ordenoSourceCode);
			if (batchTasks.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "生成分拣批次错误");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", batchTasks.size());
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 导向作业批次页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toBatchListPage")
	public String toBatchListPage(Model model, ServletRequest request) {
		try {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String customerCode = curUser.customerCode;

			List<Customers> customers = this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customers", customers);
			if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
				customerCode = customers.get(0).getCustomerCode();
			}
			Customers customer = this.customersService.findByCustomerCode(customerCode);
			if (StringUtils.isEmpty(customerCode)) {
				return "work/gather/batchList";
			}

			// 集发目的地网点
			List<AreaGroup> areaGroups = this.areaGroupService.loadAreaGroupByAuthority(customerCode);//loadByWarehouseType("paiu");
			model.addAttribute("areaGroups", areaGroups);

			List<AreaGroup> wmList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
			model.addAttribute("wmList", wmList);

			// 封装查询参数
			Map<String, Object> searchParams = new HashMap<String, Object>();
			if (StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)) {
				searchParams.put("customerCode", curUser.customers);
			}else if (StatusEnums.user_type_customer.getStatus().equals(curUser.userType)) {
				searchParams.put("customerCode", curUser.customerCode);
			}
			
			searchParams.put("status", "pending"); // 批次状态 (1.创建作业批次 2.创建作业任务
													// 3.拣货任务分配完 4.拣货任务完成
													// 5.包装任务完成 6.发货任务完成)

			// 查询未分配任务的作业批次
			List<BatchTask> batchList = this.batchTaskService.loadBatch(searchParams);
			model.addAttribute("batchList", batchList);
			model.addAttribute("customerCode", customerCode);
			model.addAttribute("customer", customer);
			model.addAttribute("_status", "1");

		} catch (Exception e) {
			
			log.error("error",e);
		}
		return "work/gather/batchList";
	}

	/**
	 * 导向创建任务页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toCreateTask/{batchCode}", method = RequestMethod.GET)
	public String toCreateTask(@PathVariable("batchCode") String batchCode,
			Model model) {
		try {
			// 作业批次
			BatchTask batch = this.batchTaskService.loadBatchByCode(batchCode);
			if (batch == null) {
				return "work/gather/createTask";
			}
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			String customerCode = batch.getCustomerCode();
			Customers customer = this.customersService.findByCustomerCode(customerCode);
			model.addAttribute("customer", customer);
			model.addAttribute("curUser", curUser);

		
			model.addAttribute("batch", batch);

			// 查询未处理订单
			List<BackupTaskOrdeno> orderList = this.backupTaskOrdenoService.findByBackupTaskCodeAndBatchTaskCode(null, batchCode);
			model.addAttribute("orderList", orderList);

			// 查询已生成的任务
			List<BackupTask> taskList = this.backupTaskService.findbyBatchCode(batchCode);
			model.addAttribute("taskList", taskList);

		} catch (Exception e) {
			
			log.error("error",e);
		}
		return "work/gather/createTask";
	}

	/**
	 * 作业任务预览
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "preTask", method = RequestMethod.POST)
	public String preTask(ServletRequest request, HttpServletResponse response,
			Model model) {
		try {			

			String tactics = request.getParameter("tactics"); // 策略
			Integer taskcount = Integer.valueOf(request.getParameter("taskcount")); // 任务容量
			String batchCode = request.getParameter("batchCode"); // 任务批次
			String pickType = request.getParameter("pickType"); // 任务类型 (single
																// 单件 mulit: 多件)

			BatchTask batch = this.batchTaskService.loadBatchByCode(batchCode);
			model.addAttribute("batch", batch);
			String customerCode = batch.getCustomerCode();
			Customers customer = this.customersService.findByCustomerCode(customerCode);
			model.addAttribute("customer", customer);
			Map<String, List<BatchTask>> map = new HashMap<String, List<BatchTask>>();
			List<BackupTaskOrdeno> orderList = this.backupTaskOrdenoService.findByBackupTaskCodeAndBatchTaskCode(null, batchCode);

			List<BatchTask> taskList = null;

			if("0".equals(customer.getSubStock())){
				if ("single".equals(pickType)) {
					taskList = this.batchTaskService.createTask_single_1(orderList,batch, tactics, taskcount);
					map.put("taskList", taskList);
					model.addAttribute("taskList", taskList);
					return "work/gather/preTask_single_1";
				} else if ("multiple".equals(pickType)) {
					taskList = this.batchTaskService.createTask_multi_1(orderList,batch, tactics, taskcount);
					map.put("taskList", taskList);
					model.addAttribute("taskList", taskList);
					return "work/gather/preTask_multi_1";
				}
			}else if("1".equals(customer.getSubStock())){
				if ("single".equals(pickType)) {
					taskList = this.batchTaskService.createTask_single(orderList,batch, tactics, taskcount);
					map.put("taskList", taskList);
					model.addAttribute("taskList", taskList);
					return "work/gather/preTask_single";
				} else if ("multiple".equals(pickType)) {
					taskList = this.batchTaskService.createTask_multi(orderList,batch, tactics, taskcount);
					map.put("taskList", taskList);
					model.addAttribute("taskList", taskList);
					return "work/gather/preTask_multi";
				}

			}
			
			
		} catch (Exception e) {
			log.error("error",e);
		}

		return null;
	}
	

	/**
	 * 查询作业批次
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryWorkBatch")
	public String queryWorkBatch(@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,Model model, ServletRequest request,
			ServletResponse response) throws Exception {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "_");
		String fromDateStr = (String) searchParams.get("fromDate");
		String toDateStr = (String) searchParams.get("toDate");
		String batchType = (String) searchParams.get("batchType");
		String workType = (String) searchParams.get("workType");
		String warehouseCode = (String) searchParams.get("warehouseCode");
		String customerCode = (String) searchParams.get("customerCode");
		String areaGroupCode = (String) searchParams.get("areaGroupCode");
		// 查找商户组
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("customers", customerList);

		if (customerCode == null) { // 派友用户
			customerCode = customerList.get(0).getCustomerCode();
		}
		Customers customer = this.customersService
				.findByCustomerCode(customerCode);
		model.addAttribute("customer", customer);

		// 集发目的地网点
		List<AreaGroup> areaGroups = this.areaGroupService.loadAreaGroupByAuthority(customerCode);//loadByWarehouseType("paiu");
		model.addAttribute("areaGroups", areaGroups);

		// 发往网点
		List<AreaGroup> wmList = this.areaGroupService.loadAreaGroupByAuthority(curUser, customerCode);
		model.addAttribute("wmList", wmList);

		Date fromDate = null;
		Date toDate = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		if (StringUtils.isNotEmpty(fromDateStr)) {
			fromDate = sdf.parse(fromDateStr);
		}
		if (StringUtils.isNotEmpty(toDateStr)) {
			toDate = sdf.parse(toDateStr);
		}

		// 封装查询参数
		searchParams.put("customerCode", customerCode);
		searchParams.put("fromDate", fromDate);
		searchParams.put("toDate", toDate);
		searchParams.put("batchType", batchType);
		searchParams.put("workType", workType);
		searchParams.put("warehouseCode", warehouseCode);
		searchParams.put("areaGroupCode", areaGroupCode);

		// 查询作业批次
		Page<BatchTask> workBatchList = this.batchTaskService.loadBatch(pageNumber,pageSize,sortType,searchParams);
		model.addAttribute("pageBatchList", workBatchList);

		return "work/gather/batchList";
	}

}
